package com.debao.quartz.task;


import com.debao.common.constant.Constants;
import com.debao.system.domain.Coach;
import com.debao.system.domain.CourseCard;
import com.debao.system.service.ICoachService;
import com.debao.system.service.ICourseCardOrderService;
import com.debao.system.service.ICourseCardService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 统计讲师的课程和学员数量
 */
@Component("censusTask")
public class CensusTask {

    @Resource
    private ICourseCardService courseCardService;
    @Resource
    private ICoachService coachService;
    @Resource
    private ICourseCardOrderService cardOrderService;

    @Transactional(rollbackFor = Exception.class)
    public void census() {
        try {
            List<Coach> coachList = coachService.selectCoachList(new Coach().setStatus(Constants.STATUS_1));
            if (coachList == null || coachList.isEmpty()) {
                return; // 为空或null时直接返回，避免后续操作引发异常
            }
            //批量查询 和更新减少数据库的访问
            List<Coach> coaches = coachList.stream().map(coach -> {
                Long coachId = coach.getId();
                //根据coachId 查询相关的courseCard 和order信息
                List<CourseCard> courseCardList = courseCardService.selectCourseCardList(new CourseCard().setCoachId(coachId).setOnline(1L));
                int courseNum = courseCardList.size();
                int studentNum = 0;
                if (!courseCardList.isEmpty()) {
                    studentNum = courseCardList.stream()
                            .mapToInt(courseCard -> cardOrderService.selectCourseCount(courseCard.getId()))
                            .sum();
                }
                //构造更新后的Coach对象
                Coach newCoach = new Coach();
                newCoach.setId(coachId);
                newCoach.setCourseNum(courseNum);
                newCoach.setStudentNum(studentNum);
                return newCoach;
            }).collect(Collectors.toList());
            // 在数据库层面保证一致性，此处需要开启事务
            coachService.updateCoachesInBatch(coaches);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Error executing censusCourse task", e);
        }
    }

}
